
#import "UserDetailsViewController.h"
#import "ClientListViewController.h"
#include "BandwidthViewController.h"
#import "UserTorrentListViewController.h"
#import "AppDelegate.h"

@implementation UserDetailsViewController

//
// user details
//
@synthesize userDetails														= _userDetails;

//
// config
//
@synthesize userDetailsSections												= _userDetailsSections;

//
// user id
//
@synthesize userId															= _userId;

//
// init with style
//
- (id)init
{
	//
	// call super
	//
	self																	= [super initWithStyle:UITableViewStyleGrouped];
	if(!self)
		return nil;
	
	//
	// item config
	//
	typedef struct _info_item
	{
		char const*															_id;
		char const*															_title;
		char const*															_detail;
		char const*															_reuseId;
		int																	_style;
		int																	_accessory;
		bool																_selectable;
		bool																_localizable;
	}info_item;
	
	//
	// section config
	//
	typedef struct _section_info
	{
		char const*															_title;
		int																	_count;
		info_item*															_items;
	}section_info;
	
	//
	// basic
	//
	static info_item basic[] = 
	{
		{"uid",			"User ID",			"userId",				"v1",		UITableViewCellStyleValue1,			UITableViewCellAccessoryNone,					false,		false},
		{"name",		"Name",				"userName",				"v1",		UITableViewCellStyleValue1,			UITableViewCellAccessoryNone,					false,		false},
		{"gender",		"Gender",			"gender",				"v1",		UITableViewCellStyleValue1,			UITableViewCellAccessoryNone,					false,		true},
		{"class",		"Class",			"userClass",			"v1",		UITableViewCellStyleValue1,			UITableViewCellAccessoryNone,					false,		true},
		{"join",		"Join Date",		"joinDate",				"v1",		UITableViewCellStyleValue1,			UITableViewCellAccessoryNone,					false,		false},
	};
	
	//
	// activity
	//
	static info_item activity[] = 
	{
		{"last_date",	"Last Date",		"lastDate",				"v1",		UITableViewCellStyleValue1,			UITableViewCellAccessoryNone,					false,		false},
		{"last_ip",		"Last IP",			"lastIp",				"v1",		UITableViewCellStyleValue1,			UITableViewCellAccessoryNone,					false,		false},
		{"clients",		"Torrent Clients",	0,						"d>",		UITableViewCellStyleDefault,		UITableViewCellAccessoryDisclosureIndicator,	true,		false},
	};
	
	//
	// traffic
	//
	static info_item traffic[] = 
	{
		{"uploaded",	"Uploaded Size",	"uploadedSize",			"v1",		UITableViewCellStyleValue1,			UITableViewCellAccessoryNone,					false,		false},
		{"downloaded",	"Downloaded Size",	"downloadedSize",		"v1",		UITableViewCellStyleValue1,			UITableViewCellAccessoryNone,					false,		false},
		{"ratio",		"Share Ratio",		"shareRatio",			"v1",		UITableViewCellStyleValue1,			UITableViewCellAccessoryNone,					false,		false},
		{"seed_time",	"Seeding Time",		"seedTime",				"v1",		UITableViewCellStyleValue1,			UITableViewCellAccessoryNone,					false,		false},
		{"leech_time",	"Leeching Time",	"leechTime",			"v1",		UITableViewCellStyleValue1,			UITableViewCellAccessoryNone,					false,		false},
		{"time_ratio",	"Se./Le. TimeRatio","timeRatio",			"v1",		UITableViewCellStyleValue1,			UITableViewCellAccessoryNone,					false,		false},
		{"bandwidth",	"Bandwidth",		0,						"d>",		UITableViewCellStyleDefault,		UITableViewCellAccessoryDisclosureIndicator,	true,		false},
	};
	
	//
	// karma
	//
	static info_item karma[] =
	{
		{"up_karma",	"Uploading Karma",	"uploadKarma",			"v1",		UITableViewCellStyleValue1,			UITableViewCellAccessoryNone,					false,		false},
		{"down_karma",	"Downloading Karma","downloadKarma",		"v1",		UITableViewCellStyleValue1,			UITableViewCellAccessoryNone,					false,		false},
		{"uCoin",		"UCoin",			"uCoin",				"v1",		UITableViewCellStyleValue1,			UITableViewCellAccessoryNone,					false,		false},
		{"karma",		"Karma",			"karma",				"v1",		UITableViewCellStyleValue1,			UITableViewCellAccessoryNone,					false,		false},
		{"real_ratio",	"Real Share Ratio",	"realShareRatio",		"v1",		UITableViewCellStyleValue1,			UITableViewCellAccessoryNone,					false,		false},
	};
	
	//
	// torrent
	//
	static info_item torrent[] = 
	{
		{"Seeding",		"Seeding",			0,						"d>",		UITableViewCellStyleDefault,		UITableViewCellAccessoryDisclosureIndicator,	true,		false},
		{"Leeching",	"Leeching",			0,						"d>",		UITableViewCellStyleDefault,		UITableViewCellAccessoryDisclosureIndicator,	true,		false},
		{"Uploaded",	"Uploaded",			0,						"d>",		UITableViewCellStyleDefault,		UITableViewCellAccessoryDisclosureIndicator,	true,		false},
		{"Completed",	"Completed",		0,						"d>",		UITableViewCellStyleDefault,		UITableViewCellAccessoryDisclosureIndicator,	true,		false},
		{"Incomplete",	"Incomplete",		0,						"d>",		UITableViewCellStyleDefault,		UITableViewCellAccessoryDisclosureIndicator,	true,		false},
	};
	
	//
	// all sections
	//
	static section_info sections[5] = 
	{
		{"Basic",		sizeof(basic) / sizeof(basic[0]),		basic},
		{"Activity",	sizeof(activity) / sizeof(activity[0]), activity},
		{"Traffic",		sizeof(traffic) / sizeof(traffic[0]),	traffic},
		{"Karma",		sizeof(karma) / sizeof(karma[0]),		karma},
		{"Torrent",		sizeof(torrent) / sizeof(torrent[0]),	torrent},
	};
	
	//
	// create user detail info
	//
	int count																= sizeof(sections) / sizeof(sections[0]);
	self.userDetailsSections												= [[[NSMutableArray alloc] initWithCapacity:count] autorelease];
	for(int i = 0; i < count; i ++)
	{
		NSMutableDictionary* sectionInfo									= [[NSMutableDictionary alloc] initWithCapacity:2];
		NSMutableArray* contentArray										= [[NSMutableArray alloc] initWithCapacity:sections[i]._count];
		for(int j = 0; j < sections[i]._count; j ++)
		{
			NSMutableDictionary* item										= [[NSMutableDictionary alloc] initWithCapacity:6];
			[item setObject:[NSString stringWithCString:sections[i]._items[j]._id encoding:NSUTF8StringEncoding] forKey:@"id"];
			[item setObject:[NSString stringWithCString:sections[i]._items[j]._title encoding:NSUTF8StringEncoding] forKey:@"title"];
			[item setObject:[NSString stringWithCString:sections[i]._items[j]._reuseId encoding:NSUTF8StringEncoding] forKey:@"reuse"];
			[item setObject:[NSNumber numberWithInt:sections[i]._items[j]._style] forKey:@"style"];
			[item setObject:[NSNumber numberWithInt:sections[i]._items[j]._accessory] forKey:@"accessory"];
			
			if(sections[i]._items[j]._detail)
				[item setObject:[NSString stringWithCString:sections[i]._items[j]._detail encoding:NSUTF8StringEncoding] forKey:@"detail"];
			
			[item setObject:[NSNumber numberWithBool:sections[i]._items[j]._selectable] forKey:@"selectable"];
			[item setObject:[NSNumber numberWithBool:sections[i]._items[j]._localizable] forKey:@"localizable"];
			
			[contentArray addObject:item];
			[item release];
		}
		
		[sectionInfo setObject:[NSString stringWithCString:sections[i]._title encoding:NSUTF8StringEncoding] forKey:@"title"];
		[sectionInfo setObject:contentArray forKey:@"content"];
		[contentArray release];
		[self.userDetailsSections addObject:sectionInfo];
		[sectionInfo release];
	}
	
	//
	// setup title,image http://app-bits.com/assets/files/iphone_toolbar_icons.zip
	//
	self.title																= NSLocalizedStringFromTable(@"User Details", @"UserDetailsViewController", nil);
	self.tabBarItem.image													= [UIImage imageNamed:@"tab_icon_user.png"];
	self.tabBarItem.title													= NSLocalizedStringFromTable(@"Home", @"UserDetailsViewController", nil);
	
	//
	// setup refresh button
	//
	self.navigationItem.rightBarButtonItem									= [[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemRefresh target:self action:@selector(refreshUserDetails:)] autorelease];
	
	return self;
}

//
// dealloc
//
- (void)dealloc
{
	self.userDetails														= nil;
	self.userDetailsSections												= nil;
	
	[super dealloc];
}

//
// reload user details
//
- (void)reloadUserDetails:(BOOL)useActivityView
{
	NexusClient* client														= [NexusClient sharedClient];
	id getUserDetailsFinished = ^void(GetUserDetailsRequest* httpRequest)
	{
		if(useActivityView)
			[ActivityView removeView];
		
		if(!httpRequest.error && httpRequest.response.statusCode == 200)
		{
			self.userDetails												= httpRequest.userDetails;
			[self.tableView reloadData];
		}
		else
		{
			NSString* message												= [httpRequest errorDescription];
			NSString* title													= NSLocalizedStringFromTable(@"Get User Details Failed", @"UserDetailsViewController", nil);
			[UIAlertView alertViewWithTitle:title message:message cancel:NSLocalizedString(@"OK", nil)];
		}
	};
	
	if(useActivityView)
		[ActivityView showActivityView:NSLocalizedStringFromTable(@"Getting User Details", @"UserDetailsViewController", nil) networking:YES];
	
	if(!self.userId)
		self.userId															= [DataCenter sharedDataCenter].userId;
	
	[client getUserDetails:self.userId callback:getUserDetailsFinished];
}

//
// relogin
//
- (void)relogin:(id)sender
{
	NSString* title															= NSLocalizedString(@"Confirm", nil);
	NSString* message														= NSLocalizedStringFromTable(@"Are you sure want to logout?", @"UserDetailsViewController", nil);
	id onDismiss = ^void(int buttonIndex)
	{
		self.userDetails													= nil;
		[self.tableView reloadData];
		[[DataCenter sharedDataCenter] invalidUserInfo];
		[(AppDelegate*)[[UIApplication sharedApplication] delegate] showLoginView:NO];
	};
	[UIAlertView alertViewWithTitle:title message:message cancel:NSLocalizedString(@"Cancel", nil) others:[NSArray arrayWithObjects:NSLocalizedString(@"OK", nil), nil] onDismiss:onDismiss onCancel:nil];
}

//
// view loaded
//
- (void)viewDidLoad
{
	[super viewDidLoad];
	if(self.userId)
		[self reloadUserDetails:YES];
	else
		self.navigationItem.leftBarButtonItem								= [[[UIBarButtonItem alloc] initWithTitle:NSLocalizedStringFromTable(@"Logout", @"UserDetailsViewController", nil) style:UIBarButtonItemStylePlain target:self action:@selector(relogin:)] autorelease];
}

//
// get section count
//
- (NSInteger)numberOfSectionsInTableView:(UITableView*)tableView
{
	return !self.userDetails || self.userDetails.userName.length ? self.userDetailsSections.count : 1;
}

//
// get title
//
- (NSString*)tableView:(UITableView*)tableView titleForHeaderInSection:(NSInteger)section
{
	return !self.userDetails || self.userDetails.userName.length ? NSLocalizedStringFromTable([[self.userDetailsSections objectAtIndex:section] objectForKey:@"title"], @"UserDetailsViewController", nil) : nil;
}

//
// get footer
//
- (NSString*)tableView:(UITableView*)tableView titleForFooterInSection:(NSInteger)section
{
	return !self.userDetails || self.userDetails.userName.length ? nil : NSLocalizedStringFromTable(@"Access denied\nHe(She) wants to protect personal details", @"UserDetailsViewController", nil);
}

//
// get row count
//
- (NSInteger)tableView:(UITableView*)tableView numberOfRowsInSection:(NSInteger)section
{
	return !self.userDetails || self.userDetails.userName.length ? [[[self.userDetailsSections objectAtIndex:section] objectForKey:@"content"] count] : 0;
}

//
// get cell
//
- (UITableViewCell*)tableView:(UITableView*)tableView cellForRowAtIndexPath:(NSIndexPath*)indexPath
{
	NSDictionary* contentInfo												= [[[self.userDetailsSections objectAtIndex:indexPath.section] objectForKey:@"content"] objectAtIndex:indexPath.row];
	NSString* reuseId														= [contentInfo objectForKey:@"reuse"];
	UITableViewCell* theCell												= [tableView dequeueReusableCellWithIdentifier:reuseId];
	if(!theCell)
		theCell																= [[[UITableViewCell alloc] initWithStyle:(UITableViewCellStyle)[[contentInfo objectForKey:@"style"] intValue] reuseIdentifier:reuseId] autorelease];
	
	NSString* title															= [contentInfo objectForKey:@"title"];
	theCell.textLabel.text													= NSLocalizedStringFromTable(title, @"UserDetailsViewController", nil);
	
	NSString* detail														= [contentInfo objectForKey:@"detail"];
	if(detail)
	{
		id value															= [self.userDetails valueForKey:detail];
		value																= [value isKindOfClass:[NSString class]] ? value : [value stringValue];
		theCell.detailTextLabel.text										= [[contentInfo objectForKey:@"localizable"] boolValue] ? NSLocalizedStringFromTable(value, @"UserDetailsViewController", nil) : value;;
	}
	else
	{
		theCell.detailTextLabel.text										= nil;
	}
	
	theCell.selectionStyle													= [[contentInfo objectForKey:@"selectable"] boolValue] ? UITableViewCellSelectionStyleBlue : UITableViewCellSelectionStyleNone;
	theCell.accessoryType													= (UITableViewCellAccessoryType)[[contentInfo objectForKey:@"accessory"] intValue];
	
	return theCell;
}

//
// select row
//
- (void)tableView:(UITableView*)tableView didSelectRowAtIndexPath:(NSIndexPath*)indexPath
{
	NSDictionary* contentInfo												= [[[self.userDetailsSections objectAtIndex:indexPath.section] objectForKey:@"content"] objectAtIndex:indexPath.row];
	NSString* contentId														= [contentInfo objectForKey:@"id"];
	if([contentId isEqualToString:@"clients"])
	{
		ClientListViewController* clientListViewController					= [[[ClientListViewController alloc] init] autorelease];
		clientListViewController.clientList									= self.userDetails.clientList;
		[self.navigationController pushViewController:clientListViewController animated:YES];
	}
	else if([contentId isEqualToString:@"bandwidth"])
	{
		BandwidthViewController* bandwidthViewController					= [[[BandwidthViewController alloc] initWithBandwidth:self.userDetails.bandwidth] autorelease];
		[self.navigationController pushViewController:bandwidthViewController animated:YES];
	}
	else if([contentId isEqualToString:@"Seeding"] || [contentId isEqualToString:@"Leeching"] || [contentId isEqualToString:@"Uploaded"] || [contentId isEqualToString:@"Completed"] || [contentId isEqualToString:@"Incomplete"])
	{
		UserTorrentListViewController* userTorrentListViewController		= [[[UserTorrentListViewController alloc] init] autorelease];
		userTorrentListViewController.type									= contentId;
		userTorrentListViewController.userId								= self.userId;
		[self.navigationController pushViewController:userTorrentListViewController animated:YES];
	}
}

//
// refresh user
//
- (void)refreshUserDetails:(id)sender
{
	[self reloadUserDetails:YES];
}

@end
